package com.ruoyi.web.controller;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.WxLoginBody;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.framework.config.properties.WxProperties;
import com.ruoyi.framework.utils.JSONUtil;
import com.ruoyi.framework.utils.StringUtil;
import com.ruoyi.framework.web.service.WebLoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@Slf4j
public class LoginController {

    @Autowired
    WxProperties wxProperties;

    @Autowired
    private WebLoginService loginService;


    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody)  {

        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 获取微信手机号
     * @param code
     * @return
     */
    @GetMapping("/login/getMobile/{code}")
    public AjaxResult getMobile(@PathVariable("code") String code){
        AjaxResult ajax = AjaxResult.success();
        String mobile = loginService.getMobile(code);
        ajax.put(Constants.WEIXIN_MOBILE, mobile);
        return ajax;
    }

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login/weixin")
    public AjaxResult wxLogin(@RequestBody @Validated WxLoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + wxProperties.getAppId() + "&secret=" + wxProperties.getAppSecrect()+ "&js_code=" + loginBody.getCode() + "&grant_type=authorization_code";
        String response = HttpUtils.sendGet(url);
        Map resultMap = JSONUtil.parseJSONToMap(response);
        if(!resultMap.containsKey("openid")){//获取openid有误
            throw new ServiceException("非法的openid");
        }
        String openId = StringUtil.getTrim(resultMap.get("openid"));
        loginBody.setOpenId(openId);

        // 生成令牌
        String token = loginService.wxLogin(loginBody);
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }
}
